package com.db.controller;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.db.pojo.Feedback;
import com.db.service.FeedbackService;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@Controller
@RequestMapping("/WxApi")
public class WxApiController {


    @Autowired
    private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法，简单的restful服务模板

    private final String REST_URL_PREFIX = "http://127.0.0.1:8081";

    private final String APPID = "wxdb1629d471eb5a65";

    //反馈意见单增加
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public String getUserInfo(String code,String encryptedData,String iv){

        // 请求头设置,x-www-form-urlencoded格式的数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //提交参数设置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
//        map.add("code",code);
//        map.add("encryptedData",encryptedData);
//        map.add("iv",iv);
        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxdb1629d471eb5a65&secret=0dd58dc165abf801a8a58a15b667a95b&js_code="+code+"&grant_type=authorization_code";
        String result = restTemplate.postForObject(url, request, String.class);
        JSONObject resjson = JSON.parseObject(result);
        String sessionKey = (String) resjson.get("session_key");
        String userinfo = decryptWxData(encryptedData, sessionKey, iv);
        return userinfo;


    }

    public  String decryptWxData(String encryptedData, String sessionKey, String iv) {
        try {
// 初始化

            Security.addProvider(new BouncyCastleProvider());

            SecretKeySpec spec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");

            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");

            parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);

            byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));

            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);


                return result;

            }

        } catch (Exception e) {

        }

        return null;

    }



    public String decryptWxDataOfHutool(String encryptedData, String sessionKey, String iv) {
        AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
        byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData));
        if (null != resultByte && resultByte.length > 0) {
            int padNum = resultByte[resultByte.length - 1];
            if (padNum < 1 || padNum > 32) {
                padNum = 0;
            }
            resultByte = Arrays.copyOfRange(resultByte, 0, resultByte.length - padNum);
            String result = new String(resultByte, StandardCharsets.UTF_8);
            return result;
        }
        return null;
    }

    public static void main(String[] args) {
        String encryptedData = "je8FUw5ivIMnbW/SUeJzEqb1dqiv8S1c1oJ+aVcktjnkdMcq16TLBbkiDug1Km2sxuu5nmO5j9QGLWREOAkaHwjJH/2lHliq8D3MSl9q9fE5WtNtwO0BsBh/DBhLVaRFwpwEWGhspRy9TL+PO8lezkb3E0xdZVdQKB0SbAqhDUe8k5j7fG4G6oxvvrg7DnxV8uKi67Mo1RGFAx1QjtffFw==";

        String sessionKey = "Eq5Bao4+NiiyqvVGmEFR4A==";

        String iv = "zr75JDqgcc23AKQxmzZykA==";

//        String s = decryptWxDataOfHutool(encryptedData, sessionKey, iv);
//        System.out.println(s);
//        decryptWxData(encryptedData, sessionKey, iv);

    }


}
